<?php

namespace App\Jobs\Bureau;

use App\Http\Controllers\Api\Repositories\WxNoticeRepositories;
use App\Models\Bureau\WxBureau;
use App\Models\Bureau\WxClubTeam;
use App\Models\Shop\WxShopOrder;
use App\Models\Shop\WxShopOrderGoods;
use App\Wen\Utils\Settings;
use App\Wen\Utils\StrUtils;
use App\Wen\Utils\UserUtils;
use App\Wen\Utils\Utils;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class BureauNoticeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        $now = Carbon::now();
        $before_minuters = _between_(Settings::get('app_bureau_notice_before_start', 20), 5, 1000);
        $after_minuters = 30;

        $twentyMinutesLater = $now->copy()->addMinutes($before_minuters);
        DB::table('wx_bureau')
            ->whereDate('service_date_start', '=', $now->toDateString())
            ->whereTime('service_time_start', '>=', $now->toTimeString())
            ->whereTime('service_time_start', '<', $twentyMinutesLater->toTimeString())
            ->where('is_notice_before', 0)
            ->orderBy('id', 'desc')
            ->get()->map(function ($bureau) use (&$before_minuters){
                $dateTimeStart = $bureau->service_date_start . ' ' . $bureau->service_time_start;
                $formattedStartTime = Carbon::parse($dateTimeStart)->format('Y年m月d日 H:i');
                WxClubTeam::where('bureau_id', $bureau->id)->orderBy('id', 'asc')->get()->map(function ($team, $tindex) use (&$bureau, &$formattedStartTime, &$before_minuters){
                    $members = $team->members;
                    if($members){
                        $title = '活动'.$before_minuters.'分钟后开始';
                        $key1 = '「<a href="/pagesZ/organize-bureau/details/index?id='. $bureau->id .'">'.StrUtils::limit($bureau->title, 10).'</a>」活动即将开始了';
                        // 模板消息通知
                        foreach ($members as $user_id){
                            $r = WxNoticeRepositories::addNotice(9003, $user_id,$title,$key1,100);
                            if($r){
                                Utils::templateMessage($user_id, $title, $key1, $formattedStartTime, '', '点击可查看详情',  'notice', true);
                            }
                        }
                        Utils::app_push($title, $key1, 999, ['target_type'=>6, 'target_id'=>'/pagesZ/organize-bureau/details/index?id='.$bureau->id], 'batch', $members, 0);
                    }
                });
                WxBureau::where('id', $bureau->id)->update(['is_notice_before'=>1]);
            });



        $FiveMinutesBefore = $now->copy()->subMinutes($after_minuters);
        DB::table('wx_bureau')
            ->whereDate('service_date_end', '=', $now->toDateString())
            ->whereTime('service_time_end', '<=', $now->toTimeString())
            ->whereTime('service_time_end', '>', $FiveMinutesBefore->toTimeString())
            ->where('is_notice_after', 0)
            ->orderBy('id', 'desc')
            ->get()->map(function ($bureau) use (&$after_minuters){
                $dateTimeEnd = $bureau->service_date_end . ' ' . $bureau->service_time_end;
                $formattedStartTime = Carbon::parse($dateTimeEnd)->format('Y年m月d日 H:i');
                WxClubTeam::where('bureau_id', $bureau->id)->orderBy('id', 'asc')->get()->map(function ($team, $tindex) use (&$bureau, &$formattedStartTime, &$after_minuters){
                    $members = $team->members;
                    if($members){
                        $title = '活动已结束，邀请您上传活动图集';
                        $key1 = '「<a href="/pagesZ/organize-bureau/details/index?id='. $bureau->id .'">'.StrUtils::limit($bureau->title, 10).'</a>」已经结束了';
                        // 模板消息通知
                        foreach ($members as $user_id){
                            $r = WxNoticeRepositories::addNotice(9004, $user_id,$title,$key1,100);
                            if($r){
                                Utils::templateMessage($user_id, $title, $key1, $formattedStartTime, '', '点击可查看详情',  'notice', true);
                            }
                        }
                        Utils::app_push($title, $key1, 999, ['target_type'=>6, 'target_id'=>'/pagesZ/organize-bureau/details/index?id='.$bureau->id], 'batch', $members, 0);
                    }
                });
                WxBureau::where('id', $bureau->id)->update(['is_notice_after'=>1]);
            });


        DB::table('wx_bureau')
            ->where('service_date_end', '<', $now->toDateString())
            ->orWhere(function ($query) use ($now) {
                $query->where('service_date_end', '=', $now->toDateString())
                    ->where('service_time_end', '<', $now->toTimeString());
            })
            ->where('is_auto_ship', 0)
            ->orderBy('id', 'asc')
            ->get()->map(function ($bureau){
                DB::beginTransaction();
                try {
                    // 0=正常 1=未发货 2=已发货 3=确认收货 4=已退货 5=取消 6=用户删除 7=退款中
                    $orders_ids = WxShopOrder::where('order_from', 7)->where('pay_status', 2)->where('status', 1)
                        ->where('order_goods_id', 'like', "%'".$bureau->id."'%")->pluck('id')->toArray();
                    if($orders_ids){
                        // 确实存在
                        foreach ($orders_ids as $order_id){
                            if(WxShopOrderGoods::where('order_id', $order_id)->where('state', 0)->where('goods_type', 7)->where('goods_id', $bureau->id)->count() == 1){
                                $order_good = WxShopOrderGoods::where('order_id', $order_id)->where('state', 0)->where('goods_type', 7)->where('goods_id', $bureau->id)->first();
                                WxShopOrder::where('id', $order_id)->update(['status'=>2, 'ship_at' => date('Y-m-d H:i:s', time())]);
                                $nr = '您的订单：' . $order_good['order_id'] . ' 由于未按时参加活动，现已超过活动的结束时间，系统做出自动发货处理';
                                // 发送通知
                                UserUtils::add_user_notice(6001, $order_good->buyer_user_id, '商品发货通知', $nr, 100, '', $order_id);
                            }
                        }
                    }
                    WxClubTeam::where('type', 2)->where('bureau_id', $bureau->id)->update(['is_lock'=>1]);
                    WxBureau::where('id', $bureau->id)->update(['is_auto_ship'=>1]);
                    DB::commit();
                    return $bureau;
                } catch (\Exception $e) {
                    DB::rollBack();
                    _logger_(__file__, __line__, $e->getMessage());
                    return $bureau;
                }

            });
    }
}
